package cn.lzd.ui.widgets;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.text.Layout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;
import cn.lzd.ui.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 面包屑TextView，可用以显示多级文本，各级带点击事件
 */
public class DirRecordTextView extends AppCompatTextView {
    private final static int maxLengthPerItem = 8;
    private final String dividerString = " / ";
    private List<String> mItems = new ArrayList<>();
    private IOnItemClickListener mOnItemClickListener;
    private int showSize = 0;

    public DirRecordTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setSingleLine(true);
        setEllipsize(TextUtils.TruncateAt.END);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Layout layout = getLayout();
        if (layout == null) {
            return;
        }
        if (getText().length() < 2) {
            setScaleY(1);
            return;
        }
        double lasPos = layout.getSecondaryHorizontal(getText().length() - 1);
        double secPos = layout.getPrimaryHorizontal(getText().length() - 2);
        if (lasPos == secPos) {
            // 如果最后一个字的左右被挤压了，那说明前边需要有被隐藏
            showSize--;
            setText(generateShowText());
            invalidate();
        } else {
            // 显示正常，显示
            setScaleY(1);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            Layout layout = getLayout();
            if (layout == null) {
                return false;
            }
            int nowInd = getText().length();
            for (int i = mItems.size() - 1; i >= mItems.size() - showSize; i--) {
                double right = layout.getSecondaryHorizontal(nowInd);
                nowInd -= getNeedShowItem(mItems.get(i)).length();
                double left;
                if (nowInd < 0) {
                    left = 0;
                } else {
                    left = layout.getPrimaryHorizontal(nowInd);
                }
                if (event.getX() >= left && event.getX() <= right) {
                    // 点击到了 第 i 级目录
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(i);
                    }
                    break;
                }
                nowInd -= dividerString.length();
                if (nowInd < 0) {
                    break;
                }
            }
        }
        performClick();
        return true;
    }

    public void updateItems(List<String> items) {
        setScaleY(0);
        this.mItems = new ArrayList<>(items);
        showSize = mItems.size();
        setText(generateShowText());
    }

    public void setOnItemClickListener(IOnItemClickListener onItemClickListener) {
        this.mOnItemClickListener = onItemClickListener;
    }

    private SpannableString generateShowText() {
        if (showSize > mItems.size() || mItems.size() == 0) {
            return new SpannableString("");
        }
        StringBuilder needShow = new StringBuilder();
        if (mItems.size() == showSize) {
            // 全部显示
            needShow.append(getNeedShowItem(mItems.get(0)));
            for (int i = 1; i < mItems.size(); i++) {
                needShow.append(dividerString).append(getNeedShowItem(mItems.get(i)));
            }
        } else {
            // 前边有缩略的
            needShow.append("...");
            for (int i = mItems.size() - showSize; i < mItems.size(); i++) {
                needShow.append(dividerString).append(getNeedShowItem(mItems.get(i)));
            }
        }
        SpannableString spannableString = new SpannableString(needShow);
        spannableString.setSpan(new ForegroundColorSpan(
                ContextCompat.getColor(getContext(), R.color.base_ui_warn))
                , needShow.length() - getNeedShowItem(mItems.get(mItems.size() - 1)).length()
                , needShow.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    private String getNeedShowItem(String item) {
        String needAppend;
        if (item != null && item.length() > maxLengthPerItem) {
            needAppend = item.substring(0, maxLengthPerItem) + "...";
        } else {
            needAppend = item;
        }
        return needAppend;
    }

    public interface IOnItemClickListener {
        void onItemClick(int index);
    }
}
